package com.zhxi.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhxi.common.constant.ProductConstant;
import com.zhxi.common.to.es.SkuEsModel;
import com.zhxi.gulimall.search.config.GulimallElasticsearchConfig;
import com.zhxi.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


import static com.zhxi.gulimall.search.constant.EsConstant.PRODUCE_INDEX;

/**
 * @description:
 * @author: zx
 * @date: 2024-10-16 10:11
 * @version: V1.0
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStartUp(List<SkuEsModel> skuEsModels) {
        // 保存到es
        // 建立索引 建立映射关系
        BulkResponse bulk;
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest(PRODUCE_INDEX);
            request.id(String.valueOf(skuEsModel.getSkuId()));
            request.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(request);
        }
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        boolean b = bulk.hasFailures();
        if (b) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("上架错误=>", collect);
            return b;
        }
        return true;
    }
}
